<?php

namespace App\Jobs;

use App\Models\SwtOrder;
use App\Services\WeWorkService;
use Dcat\Admin\Models\Administrator;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class NoticeUser implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    public $order_id;

    public $type; // 1 机器故障 2 设备售罄 3 订单异常

    public $msg;

    /**
     * CancelOrder constructor.
     * @param $id
     */
    public function __construct($order_id, $type, $msg = "")
    {
        $this -> order_id = $order_id;

        $this -> type = $type;

        $this -> msg = $msg;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo "发起企业微信通知\n";

        $order_info = SwtOrder::with('machine') -> firstWhere('id', $this -> order_id);

        switch($this->type) {
            case 1:
                $users = $order_info -> machine -> warning_users;
                $text = "设备故障\n";
                $text .= $this -> msg."\n";
                $text .= "订单号\n";
                $text .= $order_info -> order_sn."\n";
                $text .= "下单时间\n";
                $text .= $order_info -> created_time ." \n";
            break;
            case 2:
                $users = $order_info -> machine -> stock_out_users;
                $text = "商品售罄\n";
                $text .= $this -> msg."\n";
            break;
            case 3:
                $users = $order_info -> machine -> warning_users;
                $text = "订单异常\n";
                $text .= $this -> msg."\n";
                $text .= "订单号：\n";
                $text .= $order_info -> order_sn."\n";
                $text .= "下单时间：\n";
                $text .= $order_info -> created_at ." \n";
            break;
        }

        $text .= "设备号：".$order_info -> machine -> machine_no."\n";

        $text .= '设备名：'.$order_info -> machine -> machine_name."\n";

        $users = Administrator::whereIn('id', json_decode($users)) -> whereNotNull('we_work_uid') -> pluck('we_work_uid');

        if(!$users) {
            return;
        }

        $users = implode('|', $users -> toArray());

        try{
            $app = new WeWorkService();

            $app ->setMessage($users, $text);

            echo "发送成功";

        } catch (\Exception $e) {
            echo $e->getMessage(). $this->order_id ."\n";

            $this->fail($e -> getMessage());
        }
    }
}
